import axios from "axios"
axios.defaults.baseURL = "";
axios.defaults.timeout = 102000;

axios.interceptors.request.use(config => {
  // Do something before request is sent
  let token = localStorage.getItem("liankun_user") ? localStorage.getItem("liankun_user") : "";
  config.headers.Authorization = token;
  return config;
}, error => {
  // Do something with request error
  return Promise.reject(error);
});
axios.interceptors.response.use(response => {
  // Do something before response is sent
  // console.log(response);
  if (response.data.code == -5 || response.data.code == -3) {
    localStorage.removeItem('liankun_user')
    localStorage.removeItem('user_id')
    router.replace({ path: '/partnerLogin' })
    Message(response.data.msg)
  }
  return response.data;
}, error => {
  // Do something with response error
  return Promise.reject(error);
});



//封装的get请求方法
//url:string 请求路径
//params:Object|string 请求参数
function get(url, params = {}) {
  const token = localStorage.getItem("liankun_user") ? localStorage.getItem("liankun_user") : "";
  const user_id = localStorage.getItem('user_id') ? localStorage.getItem("user_id") : "";
  const market_id = localStorage.getItem('market_id') ? localStorage.getItem('market_id') : '';
  return new Promise((res, rej) => {
    axios({
      method: 'get',
      url,
      headers: {
        'access-token': token,
        'user-id': user_id,
        'market-id': market_id
      },
      params
    }).then(data => {
      res(data)
    }).catch(err => {
      rej(err)
    })
  })
}

function post(url, data = {}) {
  const token = localStorage.getItem("liankun_user") ? localStorage.getItem("liankun_user") : "";
  const user_id = localStorage.getItem('user_id') ? localStorage.getItem("user_id") : "";
  const market_id = localStorage.getItem('market_id') ? localStorage.getItem('market_id') : '';
  return new Promise((res, rej) => {
    axios({
      method: 'post',
      url,
      headers: {
        'access-token': token,
        'user-id': user_id,
        'market-id': market_id
      },
      data
    }).then(data => {
      res(data)
    }).catch(err => {
      rej(err)
    })
  })
}


// 封装包含上传内容的方法
// @url:上传地址
// @data:上传数据
function upload(url, data = {}) {
  const token = localStorage.getItem("liankun_user") ? localStorage.getItem("liankun_user") : "";
  const user_id = localStorage.getItem('user_id') ? localStorage.getItem("user_id") : "";
  return new Promise((res, rej) => {
    let form = new FormData();
    for (var key in data) {
      // append:向表单实例添加数据的方法
      // key: 数据的名称
      // value: 数据的值
      form.append(key, data[key]);
    }
    axios({
      method: 'post',
      url,
      data: form,
      headers: {
        "Content-Type": "multipart/form-data",
        'access-token': token,
        'user-id': user_id
      }
    }).then(data => {
      res(data)
    }).catch(err => {
      rej(err)
    })
  })
}


export default {
  get,
  post,
  upload
}